<?php

namespace app\common\model;


use app\common\exception\ApiException;

class Category extends BaseModel {
    public function image() {
        return $this->hasOne('Images', 'id', 'img_id')->field('id,url,from');
    }

    public function getImageAttr($value) {
        return str_replace('\\', '\/', $value);
    }

    public function getCategoryList($condition = []) {
        if (empty($condition['status']) && !isset($condition['status'])) {
            $condition['status'] = [
                'neq', config('code.status_delete')
            ];
        }
        $condition['parent_id'] = ['=', 0];
        $order                  = [
            'listorder' => 'asc'
        ];
        $result                 =
            $this->with(['image'])
                ->where($condition)
                ->order($order)
                ->select();
        return $result;
    }

    public function getMaxOrderNum() {
        return $this->where(['parent_id' => 0])->max('listorder');
    }

    public function getList($condition = []) {
        if (empty($condition['status']) && !isset($condition['status'])) {
            $condition['status'] = ['neq', config('code.status_delete')];
        }
        $order  = [
            'listorder' => 'asc'
        ];
        $result =
            $this->with(['image'])
                ->where($condition)
                ->field(['id', 'name', 'parent_id', 'tags', 'description', 'img_id', 'status'])
                ->order($order)
                ->select();
        if (!$result) {
            throw new ApiException('没有数据', 200, config('code.fail'));
        }
        return $result;
    }

    public function getCatCondition($parent_id) {
        if ($parent_id == 0) {
            return [];
        }
        $result = $this->where(['parent_id' => $parent_id])
            ->select();
        if (!$result) {
            return ['cat_id' => $parent_id];
        }
        $arr = [];
        foreach ($result as $k => $v) {
            array_push($arr, $v->id);
        }
        $condition['cat_id'] = ['in', $arr];
        return $condition;
    }

    public function changeStatus($id, $status) {
        $category              = $this->get($id);
        $category->status      = $status;
        return $category->save();
    }

    public function deleteCategory($id) {
        $categorys = $this->where('id', $id)
            ->whereOr('parent_id', $id)
            ->select();
        try {
            foreach ($categorys as $category) {
                $category->status = config('code.status_delete');
                $category->save();
            }
        } catch (\Exception $e) {
            throw new ApiException($e->getMessage(), 400);
        }
        return true;
    }

    public function changeListOrder($data) {
        $result = $this->saveAll($data);
        if (!$result) {
            throw new ApiException('修改顺序失败', 200, 1);
        }
        return true;
    }

    /** 根据信息id获取分类信息
     * @param $id
     * @return array
     * @throws ApiException
     */
    public function getCategoryByInfoId($id) {
        $information = model('Information')->get($id);
        if (!$information) {
            throw new ApiException('没有找到id为：' . $id . '的信息', 200, 1);
        }
        $cat_id   = $information->cat_id;
        $category = model('Category')->get(['id' => $cat_id]);
        if (!$category) {
            throw new ApiException('没有找到对应的分类栏目', 200, 1);
        }
        return [
            'cat_name' => $category['name'],
            'cat_id'   => $category['id']
        ];
    }
}